package gamedata

import (
	"encoding/json"
	"sync"

	"lottery/conf"
	"lottery/libs/mq"
	"lottery/models"
	"lottery/utils"

	"github.com/astaxie/beego/logs"
)

var once *sync.Once
var defaultGameData *GameData

func init() {
	once = new(sync.Once)
}

func GetNewGameData(platformId int) (gameDatas []*models.GameData, ok bool) {
	once.Do(func() {
		defaultGameData = NewGameData()
		go defaultGameData.Run()
	})

	return defaultGameData.GetNewGameData(platformId)
}

// 临时数据服务

type GameData struct {
	mux           *sync.RWMutex
	gameDataTopic string
	mq            mq.MessageQueue
	cache         map[int][]*models.GameData
}

func NewGameData() *GameData {
	kafkaMQ, err := mq.OpenBaseKafkaMQ()
	if err != nil {
		panic(err)
	}

	res := conf.LoadResource()
	return &GameData{
		mux:           new(sync.RWMutex),
		mq:            kafkaMQ,
		gameDataTopic: res.GameDataTopic,
		cache:         make(map[int][]*models.GameData),
	}
}

func (g *GameData) Run() {
	for data := range g.mq.ReceiveStringChan(g.gameDataTopic) {
		gameDatas := make([]*models.GameData, 0, 100)
		if err := json.Unmarshal([]byte(data), &gameDatas); err == nil {
			if len(gameDatas) > 0 {
				g.SetNewGameData(gameDatas[0].PlatformId, gameDatas)
			}
		}
	}
}

func (g *GameData) SetNewGameData(platformId int, gameDatas []*models.GameData) {
	g.mux.Lock()
	defer g.mux.Unlock()
	g.cache[platformId] = gameDatas
	return
}

func (g *GameData) GetNewGameData(platformId int) (gameDatas []*models.GameData, ok bool) {
	g.mux.RLock()
	defer g.mux.RUnlock()

	gameDatas, ok = g.cache[platformId]
	if len(gameDatas) > 0 && utils.CurrentMills()-gameDatas[0].CreateTime > 15*1000 {
		gameDatas = nil
		ok = false
		logs.Warn("平台 %d 数据过期", platformId)
		return
	}
	return
}
